package com.elepro.shoppingmall.controller;

import com.elepro.shoppingmall.service.user.UserServiceImpl;
import com.elepro.shoppingmall.entity.User;
import net.bytebuddy.utility.RandomString;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class UserLoginController {
    @Resource
    private UserServiceImpl userServiceImpl;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private BCryptPasswordEncoder encoder;

    //注册
    @PostMapping("/register")
    public boolean userRegister(@RequestBody User user, @RequestParam("code") String code, HttpServletRequest request) {
        user.setUserPicture(redisTemplate.opsForValue().get(request.getRemoteAddr() + "_userPicture"));
        int result = userServiceImpl.insertUser(user, code);
        return result == 1;
    }

    //邮箱获取验证码
    @GetMapping("/sendEmailCode")
    public void sendEmailCode(String email) {
        System.out.println(email);
        rabbitTemplate.convertAndSend("guo_exchange", "", email);
    }

    //邮箱获取验证码修改密码
    @PostMapping("/sendEmailCodeToUpdatePassword")
    public boolean sendEmailCodeToUpdatePassword(@RequestBody Map<String, String> map) {
        System.out.println(map);
        String username = map.get("username");
        String email = map.get("email");
        User user = userServiceImpl.getUserByName(username);
        if (user == null) {
            return false;
        }
        rabbitTemplate.convertAndSend("guo_exchange", "", email);
        return true;
    }

    //验证修改密码的验证码是否正确
    @PostMapping("/checkCodeIsOk")
    public boolean checkCodeIsOk(@RequestBody Map<String, String> map) {
        System.out.println(map);
        String email = map.get("email");
        String code = map.get("code");
        return code.equals(redisTemplate.opsForValue().get(email));
    }

    //修改密码
    @PostMapping("/updatePassword")
    public boolean updatePassword(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        User user = userServiceImpl.getUserByName(username);
        if (user != null)
            user.setPassword(encoder.encode(password));
        int result = userServiceImpl.updateUser(user);
        return result == 1;
    }

    //头像上传
    @PostMapping("/uploadUserPicture")
    public boolean uploadUserPicture(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        if (multipartFile.getOriginalFilename() != null) {
            String filename = RandomString.make(6) + multipartFile.getOriginalFilename();
            String userPicture = "http://127.0.0.1:8080/" + filename;
            //存入缓存
            redisTemplate.opsForValue().set(request.getRemoteAddr() + "_userPicture", userPicture, 1, TimeUnit.HOURS);
            redisTemplate.opsForValue().set(request.getRemoteAddr() + "_filename", filename, 1, TimeUnit.HOURS);
            String dirPath = "D:/image/";
            File filePath = new File(dirPath);
            if (!filePath.exists())
                System.out.println("创建：" + filePath.mkdirs());
            try {
                multipartFile.transferTo(new File(dirPath + filename));
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    //删除头像
    @PostMapping("/deleteUserPicture")
    public boolean deleteUserPicture(HttpServletRequest request) {
        String filename = redisTemplate.opsForValue().get(request.getRemoteAddr() + "_filename");
        File file = new File("D:/image/" + filename);
        return file.delete();
    }
}
